<template>
  <div class="websocket-status-panel">
    <el-card class="status-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span>WebSocket 状态</span>
        <el-button 
          style="float: right; padding: 3px 0" 
          type="text"
          @click="refreshStats"
        >
          刷新
        </el-button>
      </div>
      
      <div class="status-content">
        <!-- 连接状态 -->
        <div class="status-item">
          <span class="label">连接状态:</span>
          <el-tag 
            :type="websocketState.isConnected ? 'success' : 'danger'"
            size="small"
          >
            {{ websocketState.isConnected ? '已连接' : '未连接' }}
          </el-tag>
        </div>
        
        <!-- 重连状态 -->
        <div class="status-item" v-if="websocketState.isReconnecting">
          <span class="label">重连状态:</span>
          <el-tag type="warning" size="small">
            重连中... ({{ websocketState.reconnectCount }}/5)
          </el-tag>
        </div>
        
        <!-- 连接时间 -->
        <div class="status-item" v-if="websocketState.connectionTime">
          <span class="label">连接时间:</span>
          <span class="value">{{ formatTime(websocketState.connectionTime) }}</span>
        </div>
        
        <!-- 重连次数 -->
        <div class="status-item" v-if="websocketState.reconnectCount > 0">
          <span class="label">重连次数:</span>
          <span class="value">{{ websocketState.reconnectCount }}</span>
        </div>
        
        <!-- 消息队列 -->
        <div class="status-item" v-if="stats.messageQueueLength > 0">
          <span class="label">消息队列:</span>
          <el-tag type="info" size="small">
            {{ stats.messageQueueLength }} 条
          </el-tag>
        </div>
        
        <!-- 最后消息 -->
        <div class="status-item" v-if="websocketState.lastMessage">
          <span class="label">最后消息:</span>
          <el-tooltip 
            :content="JSON.stringify(websocketState.lastMessage, null, 2)" 
            placement="top"
          >
            <span class="value truncated">
              {{ websocketState.lastMessage.type || '未知类型' }}
            </span>
          </el-tooltip>
        </div>
        
        <!-- 最后错误 -->
        <div class="status-item" v-if="websocketState.lastError">
          <span class="label">最后错误:</span>
          <el-tooltip 
            :content="websocketState.lastError.message || websocketState.lastError" 
            placement="top"
          >
            <span class="value error truncated">
              {{ websocketState.lastError.message || '未知错误' }}
            </span>
          </el-tooltip>
        </div>
      </div>
      
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button 
          v-if="!websocketState.isConnected" 
          type="primary" 
          size="small"
          @click="connect"
          :loading="connecting"
        >
          连接
        </el-button>
        
        <el-button 
          v-if="websocketState.isConnected" 
          type="danger" 
          size="small"
          @click="disconnect"
        >
          断开
        </el-button>
        
        <el-button 
          v-if="websocketState.isConnected" 
          type="warning" 
          size="small"
          @click="manualReconnect"
          :loading="reconnecting"
        >
          重连
        </el-button>
        
        <el-button 
          type="info" 
          size="small"
          @click="clearQueue"
        >
          清空队列
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'WebSocketStatus',
  data() {
    return {
      connecting: false,
      reconnecting: false,
      stats: {
        messageQueueLength: 0
      }
    };
  },
  computed: {
    websocketState() {
      return this.$websocketState || {};
    }
  },
  mounted() {
    this.refreshStats();
    // 定时刷新统计信息
    this.statsTimer = setInterval(this.refreshStats, 5000);
  },
  beforeDestroy() {
    if (this.statsTimer) {
      clearInterval(this.statsTimer);
    }
  },
  methods: {
    /**
     * 刷新统计信息
     */
    refreshStats() {
      if (this.$websocket && this.$websocket.getWebSocketStats) {
        this.stats = this.$websocket.getWebSocketStats();
      }
    },
    
    /**
     * 连接WebSocket
     */
    async connect() {
      if (!this.userId) {
        this.$message.warning('请先设置用户ID');
        return;
      }
      
      this.connecting = true;
      try {
        await this.$initWebSocket(this.userId);
        this.$message.success('WebSocket连接成功');
      } catch (error) {
        this.$message.error(`连接失败: ${error.message}`);
      } finally {
        this.connecting = false;
      }
    },
    
    /**
     * 断开WebSocket
     */
    disconnect() {
      this.$closeWebSocket();
      this.$message.info('WebSocket已断开');
    },
    
    /**
     * 手动重连
     */
    async manualReconnect() {
      if (!this.userId) {
        this.$message.warning('请先设置用户ID');
        return;
      }
      
      this.reconnecting = true;
      try {
        await this.$websocket.manualReconnect(this.userId);
        this.$message.success('重连成功');
      } catch (error) {
        this.$message.error(`重连失败: ${error.message}`);
      } finally {
        this.reconnecting = false;
      }
    },
    
    /**
     * 清空消息队列
     */
    clearQueue() {
      if (this.$websocket && this.$websocket.clearMessageQueue) {
        this.$websocket.clearMessageQueue();
        this.$message.success('消息队列已清空');
        this.refreshStats();
      }
    },
    
    /**
     * 格式化时间
     */
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return date.toLocaleString('zh-CN');
    }
  }
};
</script>

<style scoped>
.websocket-status-panel {
  margin: 20px 0;
}

.status-card {
  max-width: 500px;
}

.status-content {
  margin-bottom: 20px;
}

.status-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
  margin-right: 12px;
}

.value {
  color: #303133;
  flex: 1;
}

.value.error {
  color: #f56c6c;
}

.value.truncated {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-buttons .el-button {
  flex: 1;
  min-width: 80px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .status-item {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .label {
    margin-bottom: 5px;
  }
  
  .action-buttons {
    flex-direction: column;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
